<?php
namespace categoria;

class categoria {

    protected $id;
    protected $name;
    protected $fatherId;
    protected $tableName;

    function __construct($iId=0)
    {
        global $config;

        $this->id = 0;
        $this->name = "";
        $this->fatherId = 0;
        $this->tableName = "`".$config["dbName"]."`.`categorias`";

        if ($iId != 0){
            $this->loadCategoria($iId);
        }
    }

    public function loadCategoria($iId)
    {
        global $db;
        $sSql = "select * from categorias where id = ".$iId;
        $res = $db->execSql($sSql);

        if ($res){
            while ($row = mysqli_fetch_assoc($res)) {
                $this->setId($row["id"]);
                $this->setName($row["nombre"]);
                $this->setFatherId($row["idpadre"]);

            }
        }
    }

    public function saveCategoria()
    {
        global $db;
        $rtrn = 0;

        $sSql = "select id from ".$this->tableName." where `nombre` = '". $this->name ."'";
        $res = $db->execSql($sSql);
        if (mysqli_num_rows($res) == 0){
            $sSql = "insert into ".$this->tableName." (`nombre`,`idpadre`) values ('".$this->name."','".$this->fatherId."') ";
            if ($db->execSql($sSql)){
                $rtrn =  $db->getInsertedId();
            }
        }else{
            $rtrn = mysqli_fetch_assoc($res)["id"];
        }

        return $rtrn;
    }

    /**
     * @param int $fatherId
     */
    public function setFatherId($fatherId)
    {
        $this->fatherId = $fatherId;
    }

    /**
     * @return int
     */
    public function getFatherId()
    {
        return $this->fatherId;
    }

    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getTableName()
    {
        return $this->tableName;
    }




}